<?php

namespace Frieza\Modules\PointShop\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Exceptions\InputErrorException;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\trade\ShopCourier as sShopCourier;
use Biz\module\Packages\Logistics\TrackingMore;
use Doraemon\model\Member;
use Doraemon\model\PointShop\GoodsBaseInfo;
use Doraemon\model\PointShop\GoodsBaseInfo as mGoodsBaseInfo;
use Doraemon\model\PointShop\GoodsExtendInfo;
use Doraemon\model\PointShop\PointOrder;
use Doraemon\model\PointShop\PointOrderLog;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\pockets\excel\ReadExcel;
use Doraemon\service\PointShop\OrderLogisticsLog;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Doraemon\tools\PointOrderNo;
use Doraemon\tools\ShopArea;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Layout\Content;
use hhz\constant\basic\UserExtendPhoneScene;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;
use Doraemon\service\PointShop\PointOrder as sPointOrder;
use Doraemon\model\Phone;
class PointOrderController
{
    public function index(Content $content, Request $request)
    {
        $params = $request->all();
        $where = $this->buildWhere($params);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $list = PointOrder::getList($where, $limit);
        $total = PointOrder::countNum($where);
        $list = $this->format($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize,
            'keyName' => 'goods_id'
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($where) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->tools(function (Grid\Tools $tools) use ($where) {
                $modelDownUrl = '/admin/pointShop/order/downExcelModel?condition=' . base64_encode(json_encode($where));
                $tools->append("<a href='{$modelDownUrl}' class='btn button-success'><i class='fa fa-file-excel-o'></i>>导入模板</a>");
                $downUrl = '/admin/pointShop/order/downExcel?condition=' . base64_encode(json_encode($where));
                $tools->append("<a href='{$downUrl}' class='btn button-success'><i class='fa fa-file-excel-o'></i>>批量导出</a>");
                $upUrl = '/admin/pointShop/order/importExcel';
                $tools->append('<a href="javascript:layer.open({
                                type: 2,
                                title: \'批量发货\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $upUrl . '\'
                            });" class="btn button-success"><i class="fa fa-upload"></i>批量发货</a><br/>'
                );
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('order_no', '订单号');
                    $filter->equal('consignee_phone_encrypt', '手机号');
                    $filter->between('pay_time', '下单时间')->datetime();
                    $filter->between('logistics_time', '发货时间')->datetime();
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('aaaa', [
                        'uid' => '用户ID',
                        'nick' => '用户昵称'
                    ]);
                    $filter->equal('title', '商品名称');
                    $filter->equal('status', '订单状态')->select(PointOrder::STATUS_MAP);
                    $filter->equal('brand_id', '品牌')->select(GoodsBaseInfo::BRAND_MAP);
                });
            });

            $grid->column('order_no', '订单号');
            $grid->column('title', '商品名称')->width(200);
            $grid->column('pay_time', '下单时间');
            $grid->column('confirm_time', '收货时间');
            $grid->column('pay_point_price', '订单积分');
            $grid->column('nick', '用户昵称');
            $grid->column('uid', 'uid');
            $grid->column('brand_id', '品牌')->display(function ($released) {
                return GoodsBaseInfo::BRAND_MAP[$released];
            });
            $grid->column('status', '展示状态')->display(function ($released) {
                return PointOrder::STATUS_MAP[$released];
            })->label([0 => 'danger', 1 => 'success']);
            Admin::script($this->expressPopup());
            $grid->actions(function ($actions) {
                $actions->row->setKeyName('id');
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                $actions->prepend('<a href="edit' . '?all=' . base64_encode((string)json_encode($actions->row->getAttributes())) . '" > 查看详情 </a>');
                if ($actions->row->brand_id != GoodsBaseInfo::BRAND_VIRTUAL ) {
                    $actions->prepend('<a class="express" data-phone="' . $actions->row->consignee_phone_encrypt . '" data-name="' . $actions->row->consignee_name . '" data-address="' . $actions->row->consignee_address . '" data-orderno="' . $actions->row->order_no . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">&nbsp;收货地址&nbsp;</a>');
                    $actions->prepend('<a class="addExpress" data-id="' . $actions->row->id . '" data-company="' . $actions->row->express_company . '" data-fee="' . $actions->row->shipping_fee . '" data-logistics="' . $actions->row->order_logistics_no . '" data-nick="' . $actions->row->nick . '" data-order="' . $actions->row->order_no . '" href="javascript:void(0);">发货</a>');
                }
            });
        });
        return $content
            ->header('积分商城订单')
            ->breadcrumb(['text' => '积分商城订单', 'url' => '/admin/pointShop/order'])
            ->body($listGrid);
    }

    public function expressPopup()
    {
        return <<<SCRIPT
            $('.express').unbind('click').click(function() {
                var consignee_name = $(this).data('name');
                var consignee_phone_encrypt = $(this).data('phone');
                var address = $(this).data('address');
                var order_no = $(this).data('orderno');
                var id = $(this).data('id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '收货信息',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['500px', '400px'],
                    content: 'address/'+id + '?consignee_phone_encrypt=' + consignee_phone_encrypt + '&consignee_name='+consignee_name + '&address='+address + '&order_no='+order_no,
                    end: function () {
                    }
                });
		    });
            $('.addExpress').unbind('click').click(function() {
                var id = $(this).data('id');
                var nick = $(this).data('nick');
                var order = $(this).data('order');
                var express_company = $(this).data('company');
                var order_logistics_no = $(this).data('logistics');
                var shipping_fee = $(this).data('fee');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '发货',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['700px', '600px'],
                    content: 'addExpress/'+id + '?nick=' + nick + '&order='+order + '&express_company='+express_company + '&order_logistics_no='+order_logistics_no + '&shipping_fee='+shipping_fee,
                    end: function () {
                    }
                });
		    });
SCRIPT;
    }

    //添加发货弹窗
    public function addExpress(Request $request, WorkContent $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('发货')
            ->body($this->addExpressAction($request, $id));
    }

    public function addExpressAction($request, $id)
    {
        $courierList = sShopCourier::getCourierFileList();
        $courier = [];
        $data['id'] = $id;
        $data['order_no'] = $request['order'];
        $data['nick'] = $request['nick'];
        $data['express_company'] = $request['express_company'] ?: '';
        $data['order_logistics_no'] = $request['order_logistics_no'] ?: '';
        $data['nick'] = $request['nick'];
        $data['shipping_fee'] = $request['shipping_fee'];
        foreach ($courierList as $item) {
            if (empty($item['trackingmore_code'])) {
                continue;
            }
            $key = $item['trackingmore_code'] . '~%~' . $item['courier_name'];
            $courier[$key] = $item['courier_name'];
            if ($item['courier_name'] == $data['express_company']) {
                $data['express_company'] = $key;
            }
        }

        $form = new Form($data);
        $form->hidden('id', 'id');
        $form->hidden('nick', 'nick');
        $form->hidden('order_no', '订单号');
        $form->text('order_no', '订单号')->disable()->required();
        $form->text('nick', '昵称')->disable()->required();
        $form->number('shipping_fee', '实际运费')->required();
        $form->select('express_company', '物流公司')->required()->options($courier);
        $form->text('order_logistics_no', '物流单号')->required();
        $form->action('/admin/pointShop/express/save');

        return $form->render();
    }

    public function address(Request $request, WorkContent $content)
    {
        $data['consignee_phone_encrypt'] = $request['consignee_phone_encrypt'];
        $data['address'] = $request['address'];
        $data['consignee_name'] = $request['consignee_name'];
        $data['order_no'] = $request['order_no'];
        // 查询物流信息
        $logisticsInfo = OrderLogisticsLog::getInfoByOrderNo($data['order_no']);
        $msg = '';
        if (!empty($logisticsInfo['logistics_info'])) {
            foreach ($logisticsInfo['logistics_info'] as $item) {
                $msg = $msg . "<p>" . $item['accept_station'] . $item['accept_time'] . "<p>" . "\r\n";
            }
        }
        $data['express'] = $msg;
        $form = new Form($data);
        $form->disableSubmit();
        $form->disableReset();
        $form->display('consignee_name', '收货人')->disable();
        $form->display('address', '收货地址')->disable();
        $form->display('consignee_phone_encrypt', '收货人手机号')->disable();
        $form->display('express', '物流信息');
        return $content
            ->body($form->render());
    }


    public function buildWhere($params)
    {
        $where = [];
        if ($params['title']) {
            $where['AND']['title[~]'] = $params['title'];
        }
        // 把手机号转换为数字
        if (($params['consignee_phone_encrypt'])) {
            $phone = Phone::addExtendPhone($params['consignee_phone_encrypt'], UserExtendPhoneScene::POINT_SHOP_CONSIGNEE_PHONE);
            $where['AND']['consignee_phone_encrypt'] = $phone;
        }
        if ($params['order_no']) {
            $where['AND']['order_no'] = $params['order_no'];
        }
        $addTime = $params['pay_time'];
        if ($addTime['start'] && $addTime['end']) {
            $start = $addTime['start'];
            $end = $addTime['end'];
            $where['AND']['pay_time[<>]'] = [strtotime($start), strtotime($end)];
        }
        $logisticsTime = $params['logistics_time'];
        if ($logisticsTime['start'] && $logisticsTime['end']) {
            $start = $logisticsTime['start'];
            $end = $logisticsTime['end'];
            $where['AND']['logistics_time[<>]'] = [strtotime($start), strtotime($end)];
        }
        if ($params['status']) {
            $where['AND']['status'] = $params['status'];
        }
        if ($params['brand_id']) {
            $where['AND']['brand_id'] = $params['brand_id'];
        }
        if ($params['uid']) {
            $where['AND']['uid'] = $params['uid'];
        }
        if ($params['nick']) {
            $uid = Member::getUidByNick($params['nick']);
            $where['AND']['uid'] = $uid;
        }
        $where['ORDER'] = ['addtime' => 'DESC'];
        return $where;
    }

    /**
     * 详情页
     * @param Content $content
     * @param Request $request
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, Request $request, int $id = 0)
    {
        $all = $request->all()['all'];
        $data = json_decode(base64_decode($all), true);
        $data['status'] = PointOrder::STATUS_MAP[$data['status']];
        $brandId = $data['brand_id'];
        $data['brand_id'] = mGoodsBaseInfo::BRAND_MAP[$data['brand_id']];
        // 查询物流信息
        $logisticsInfo = OrderLogisticsLog::getInfoByOrderNo($data['order_no']);
        $msg = '';
        if (!empty($logisticsInfo['logistics_info'])) {
            foreach ($logisticsInfo['logistics_info'] as $item) {
                $msg = $msg . "<p>" . $item['accept_station'] . $item['accept_time'] . "<p>" . "\r\n";
            }
        }

        $data['express'] = $msg;
        $data['brand_id_raw'] = $brandId;
        $form = new Form($data);
        $form->fieldset('订单基本信息', function (Form $form) {
            $form->display('order_no', '订单号');
            $form->display('status', '订单状态');
            $form->display('pay_time', '兑换时间');
            $form->display('nick', '用户昵称');
        });
        // 京东卡没有发货
        if ($brandId != mGoodsBaseInfo::BRAND_VIRTUAL) {
            $form->fieldset('收货信息', function (Form $form) {
                $consigneeProvince = ShopArea::locationCodeOfProvince('86');
                $consigneeCity = $form->data()['consignee_province'] > 0 ? ShopArea::locationCodeOfProvince($form->data()['consignee_province']) : [];
                $consigneeArea = $form->data()['consignee_city'] > 0 ? ShopArea::locationCodeOfProvince($form->data()['consignee_city']) : [];
                if ($form->data()['status'] == PointOrder::STATUS_MAP[PointOrder::STATUS_NORMAL]) {
                    $form->text('consignee_name', '收货人');
                    $form->text('consignee_phone_encrypt', '收货手机号');
                    $form->select('consignee_province', '省份')->options($consigneeProvince)->load('consignee_city', route('order.area'));
                    $form->select('consignee_city', '城市')->options($consigneeCity)->load('consignee_area', route('order.area'));
                    $form->select('consignee_area', '区县')->options($consigneeArea);
                    $form->text('consignee_info_address', '详细地址');
                } else {
                    $form->display('consignee_name', '收货人');
                    $form->display('consignee_phone_encrypt', '收货手机号');
                    $form->select('consignee_province', '省份')->options($consigneeProvince)->disable();
                    $form->select('consignee_city', '城市')->options($consigneeCity)->disable();
                    $form->select('consignee_area', '区县')->options($consigneeArea)->disable();
                    $form->text('consignee_info_address', '详细地址')->disable();
                }
                $form->display('express', '物流信息');
            });
        }
        $form->hidden('brand_id_raw');
        $form->fieldset('商品信息', function (Form $form) {
            $form->display('title', '商品名');
            $form->display('brand_id', '商品品牌');
            $form->display('point_price', '积分兑换价格');
        });
        $form->fieldset('备注信息', function (Form $form) {
            $form->text('remarks', '备注')->placeholder('不多于255字符');
        });

        if ($data['id']) {
            $form->fieldset('订单操作', function (Form $form) use ($data) {
                Admin::script($this->offOrderJs($data['id']));
                if ($data['status'] == '订单关闭') {
                    $form->html('<span class="community_category btn btn-sm btn-success" >订单已关闭</span>');
                } else {
                    $form->html('<span class="community_category btn btn-sm btn-success" id="offOrder">关闭订单</span>');
                }
            });
        }

        $form->disableReset();
        $form->action('/admin/pointShop/order/save?id=' . $data['id']);
        return $content->header('订单查看')
            ->breadcrumb(['text' => '订单列表', 'url' => 'pointShop/order'], ['text' => '订单列表'])
            ->row($form->render());
    }

    public function offOrderJs($id)
    {
        return <<<SCRIPT
            $('#offOrder').unbind('click').click(function() {
            var id = {$id};
            let url = '/admin/pointShop/changeOrderInfo';
            var that = $(this)
            let params = {
                id:id
            };
            var text = that.text();
            if(text == '订单已关闭'){
                layer.msg('订单已是关闭状态');
                return '';
            }
            swal({
                title: "确定关闭订单吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                   $.post(url, params , function (result) {              
                         if (result.status == 0){
                            layer.msg('操作失败');                              
                        } else {
                            that.text('订单已关闭')
                            layer.msg('操作成功');
                        }
                    });
                }
                });
            });
SCRIPT;
    }

    public function changeOrderInfo(Request $request)
    {
        $param = $request->all();
        $id = $param['id'];
        $data['status'] = PointOrder::STATUS_OFF;
        $code = sPointOrder::changeOrderInfoById($data, $id);
        return response()->json(compact('code'));
    }

    public function save(Request $request)
    {
        $params = $request->all();
        if (!empty($params['remarks']) && strlen($params['remarks']) > 255) {
            throw new InputErrorException('不能大于255字符', InputErrorException::DEFAULT_CODE, 'remarks');
        }
        if (!empty($params['consignee_info_address']) && strlen($params['consignee_info_address']) > 255) {
            throw new InputErrorException('不能大于255字符', InputErrorException::DEFAULT_CODE, 'consignee_info_address');
        }
        $adminName = Admin::user()->name;
        Log::info('订单修改用户收货地址', [$params, $adminName]);
        if ($params['brand_id_raw'] != GoodsBaseInfo::BRAND_VIRTUAL) {
            $province = ShopArea::locationId2Name($params['consignee_province']);
            $city = ShopArea::locationId2Name($params['consignee_city']);
            $area = ShopArea::locationId2Name($params['consignee_area']);
            $params['consignee_address'] = $province . $city . $area . $params['consignee_info_address'];
            $params['consignee_address'] = str_replace('市辖区', '', $params['consignee_address']);
            if (empty($params['consignee_name']) || empty($params['consignee_phone_encrypt']) || empty($params['consignee_province']) || empty($params['consignee_city']) || empty($params['consignee_area']) || empty($params['consignee_info_address']) || empty($params['consignee_address'])) {
                Log::info('point-order-log', [$params, '地址异常']);
                $error = new MessageBag([
                    'title' => '参数不正确，请重试'
                ]);
                return back()->with(compact('error'))->withInput();
            }
            // todo 加密
            $phone = Phone::addExtendPhone($params['consignee_phone_encrypt'], UserExtendPhoneScene::POINT_SHOP_CONSIGNEE_PHONE);
            $id = PointOrder::editById($params['id'], ['remarks' => $params['remarks'], 'consignee_province' => $params['consignee_province'],
                'consignee_city' => $params['consignee_city'], 'consignee_area' => $params['consignee_area'],
                'consignee_info_address' => $params['consignee_info_address'], 'consignee_address' => $params['consignee_address']
                , 'consignee_name' => $params['consignee_name'], 'consignee_phone_encrypt' => $phone
            ]);
        } else {
            $id = PointOrder::editById($params['id'], ['remarks' => $params['remarks'],]);
        }

        if (empty($id)) {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect("/admin/pointShop/order")->with(compact('success'));
    }

    /**
     * @param Request $request
     * @return RedirectResponse|Redirector|void
     * @throws InputErrorException
     * @throws \Exception
     */
    public function saveAddress(Request $request)
    {
        $params = $request->all();
        if (!empty($params['shipping_fee']) && $params['shipping_fee'] < 0) {
            throw new InputErrorException('不可小于0', InputErrorException::DEFAULT_CODE, 'shipping_fee');
        }
        if (empty($params['express_company']) || mb_strlen($params['express_company']) > 50) {
            throw new InputErrorException('请填写快递公司', InputErrorException::DEFAULT_CODE, 'express_company');
        }
        if (empty($params['order_logistics_no']) || mb_strlen($params['order_logistics_no']) > 50) {
            throw new InputErrorException('请填写正确快递单号', InputErrorException::DEFAULT_CODE, 'order_logistics_no');
        }
        $adminName = Admin::user()->name;
        Log::info('订单保存地址', [$params, $adminName]);
        $express = explode('~%~', $params['express_company']);

        $id = PointOrder::editById($params['id'], ['express_company' => $express[1], 'order_logistics_no' => $params['order_logistics_no'],
            'logistics_time' => time(), 'status' => PointOrder::STATUS_EXPRESS, 'shipping_fee' => $params['shipping_fee']]);
        if (empty($id)) {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        // 调用物流发货接口
        $param = [
            'logistics_channel' => TrackingMore::LOGISTICS_CHANNEL_GOODS_POINT_SHOP,
            'lang' => 'cn'
        ];
        $result = TrackingMore::createTracking($express[0], $params['order_logistics_no'], $param);
        if ($result['meta']['code'] != 200 && !$result['meta']['type']) {
            $logText = 'trackingmore创建追踪失败 原因:' . $result['meta']['message'];
        } else {
            $logText = 'trackingmore订阅成功';
        }
        // 记录发货日志
        $logData = json_encode(['carrier_code' => $express[0], 'express_company' => $express[1], 'order_logistics_no' => $params['order_logistics_no']], JSON_UNESCAPED_UNICODE);
        $log = [
            'log_data' => $logData,
            'log_type' => PointOrderLog::LOG_TYPE_1,
            'log' => $logText,
            'order_no' => $params['order_no'],
        ];
        $res = PointOrderLog::add($log);
        $uid = PointOrderNo::getOrderUid($params['order_no']);
        $data = [
            'uid' => $uid,
            'order_no' => $params['order_no'],
            'order_logistics_no' => $params['order_logistics_no'],
            'carrier_code' => $express[0],
        ];
        $OrderLogisticsLogRes = OrderLogisticsLog::add($data);
        if (empty($res) || empty($OrderLogisticsLogRes)) {
            $error = new MessageBag([
                'title' => '物流调用失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        $data = PointOrder::getById($params['id']);
        $query = '?nick=' . $params['nick'] . '&order=' . $data['order_no'] . '&express_company=' . $data['express_company'] . '&order_logistics_no=' . $data['order_logistics_no'];
        return redirect("/admin/pointShop/addExpress/{$params['id']}" . $query)->with(compact('success'));
    }


    public function importExcel(WorkContent $content)
    {
        $form = new Form();
        $form->file('excel', '上传Excel')->required()->removable()->help('请严格按照模板格式');
        $form->action('/admin/pointShop/order/saveExcel');
        return $content->body($form);
    }

    public function saveExcel(Request $request)
    {
        $params = $request->all();
        $newFile = 'order-' . date('YmdHis') . '.xls';
        $newFilePath = '/tmp' . '/' . $newFile;
        $rs = move_uploaded_file($params['excel'], $newFilePath);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '文件保存失败'
            ]);
            return back()->with(compact('error'));
        }
        $excel = new ReadExcel($newFile);
        $excelData = $excel->getExcelDataNoHeader($newFilePath);
        //key：关键字 干预页面 内容id 干预位置 删除操作
        $excelKeyArray = ['order_no', 'title', 'point_price', 'pay_point_price', 'discount_price', 'price',
            'cost_price', 'consignee_province', 'consignee_city', 'consignee_area', 'consignee_info_address',
            'consignee_phone_encrypt', 'consignee_name', 'logistics_time', 'confirm_time',
            'pay_time', 'brand_id', 'express_company', 'order_logistics_no', 'shipping_fee', 'carrier_code'];
        $iMax = count($excelData);
        //更新数据
        $fail = new MessageBag([
            'title' => '批量导入数更新失败',
        ]);
        //检查 格式化
        for ($i = 1; $i < $iMax; $i++) {
            $excelData[$i] = array_slice($excelData[$i], 0, count($excelKeyArray));
            $singleData = array_combine($excelKeyArray, $excelData[$i]);
            if (empty($singleData['order_no'])) {
                continue;
            }
            $rules = [
                'order_logistics_no' => 'required|max:50',
                'express_company' => 'required|max:50',
                'carrier_code' => 'required',
            ];
            $message = [
                'required' => '参数 :attribute是必须传递参数.',
                'max' => '参数 :attribute 不能大于 :max.',
            ];
            //筛查 有一条不符合直接返回
            $validator = Validator::make($singleData, $rules, $message);
            if ($validator->fails()) {
                $error = new MessageBag([
                    'title' => $validator->errors()->first()
                ]);
                return back()->with(compact('error'));
                break;
            }
            if (strpos($singleData['order_logistics_no'], '.')) {
                $error = new MessageBag([
                    'title' => '物流单号不正确'
                ]);
                return back()->with(compact('error'));
                break;
            }
            $singleData['order_logistics_no'] = trim($singleData['order_logistics_no']);
            $singleData['express_company'] = trim($singleData['express_company']);
            $singleData['shipping_fee'] = trim($singleData['shipping_fee']);
            $singleData['carrier_code'] = trim($singleData['carrier_code']);
            // 如果物流公司的code不正确返回异常，把填写的物流公司名字置为表中的值
            $courierList = sShopCourier::getCourierFileList();
            $existInCourier = 0;
            foreach ($courierList as $item) {
                if ($item['trackingmore_code'] == $singleData['carrier_code']) {
                    $existInCourier = 1;
                    $singleData['express_company'] = $item['courier_name'];
                    break;
                }
            }
            if (empty($existInCourier)) {
                $error = new MessageBag([
                    'title' => '物流code不存在'
                ]);
                return back()->with(compact('error'));
                break;
            }
            $pointOrderRecord = PointOrder::getByOrderNo($singleData['order_no']);
            if ($pointOrderRecord['status'] != PointOrder::STATUS_NORMAL) {
                continue;
            }
            $resPointOrder = PointOrder::editByOrderNo($singleData['order_no'], ['order_logistics_no' => $singleData['order_logistics_no'], 'express_company' => $singleData['express_company'], 'shipping_fee' => $singleData['shipping_fee'], 'logistics_time' => time(), 'status' => PointOrder::STATUS_EXPRESS]);
            // 调用物流发货接口
            $param = [
                'logistics_channel' => TrackingMore::LOGISTICS_CHANNEL_GOODS_POINT_SHOP,
                'lang' => 'cn'
            ];
            $result = TrackingMore::createTracking($singleData['carrier_code'], $singleData['order_logistics_no'], $param);
            if ($result['meta']['code'] != 200 && !$result['meta']['type']) {
                $logText = 'trackingmore创建追踪失败 原因:' . $result['meta']['message'];
            } else {
                $logText = 'trackingmore订阅成功';
            }
            // 发货
            // 记录发货日志
            $logData = json_encode(['carrier_code' => $singleData['carrier_code'], 'express_company' => $singleData['express_company'], 'order_logistics_no' => $singleData['order_logistics_no']], JSON_UNESCAPED_UNICODE);
            $log = [
                'log_data' => $logData,
                'log_type' => PointOrderLog::LOG_TYPE_2,
                'log' => $logText,
                'order_no' => $singleData['order_no'],
            ];
            $resPointOrderLog = PointOrderLog::add($log);
            $uid = PointOrderNo::getOrderUid($singleData['order_no']);
            $data = [
                'uid' => $uid,
                'order_no' => $singleData['order_no'],
                'order_logistics_no' => $singleData['order_logistics_no'],
                'carrier_code' => $singleData['carrier_code'],
            ];
            $OrderLogisticsLogRes = OrderLogisticsLog::add($data);
            if (empty($OrderLogisticsLogRes)) {
                $error = new MessageBag([
                    'title' => '物流调用失败，请重试'
                ]);
                return back()->with(compact('error'))->withInput();
                break;
            }
            if (!$resPointOrder || !$resPointOrderLog) {
                return back()->with(compact('fail'));
            }
        }
        //更新数据
        $success = new MessageBag([
            'title' => '批量导入完成',
        ]);
        Log::info('本次excel操作人', ['name' => Admin::user()->name, $excelData]);
        return back()->with(compact('success'));
    }

    public function downExcelModel(Request $request)
    {
        $params = $request->all();
        $where = $params['condition'];
        $downExcel = new DownExcel();
        $title = '导入模板';
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $list = PointOrder::getList(json_decode(base64_decode($where), true), [], ['uid', 'order_no', 'title', 'point_price', 'pay_point_price', 'discount_price', 'price',
            'cost_price', 'consignee_province', 'consignee_city', 'consignee_area', 'consignee_info_address',
            'consignee_phone_encrypt', 'consignee_name', 'logistics_time', 'confirm_time',
            'pay_time', 'brand_id', 'express_company', 'order_logistics_no', 'shipping_fee']);
        $list = array_values($list);
        if (empty($list)) {
            $error = new MessageBag([
                'title' => '空数据，请先搜索数据'
            ]);
            return back()->with(compact('error'));
        }
        $courierList = sShopCourier::getCourierFileList();
        $courierArray = array_column($courierList, 'trackingmore_code', 'courier_name');
        $uids = array_column($list, 'uid');
        $userInfo = Member::getUserList($uids, true);
        foreach ($list as $k => &$item) {
            if ($item['brand_id'] == mGoodsBaseInfo::BRAND_VIRTUAL) {
                continue;
            }
            $item['order_logistics_no'] = $item['order_logistics_no'] . ' ';
            $item['price'] = bcdiv($item['price'], 100, 2);
            $item['cost_price'] = bcdiv($item['cost_price'], 100, 2);
            $item['consignee_province'] = ShopArea::locationId2Name($item['consignee_province']);;
            $item['consignee_city'] = ShopArea::locationId2Name($item['consignee_city']);;
            $item['consignee_area'] = ShopArea::locationId2Name($item['consignee_area']);;
            $item['confirm_time'] = $item['confirm_time'] ? date('Y-m-d H:i:s', $item['confirm_time']) : '';
            $item['logistics_time'] = $item['logistics_time'] ? date('Y-m-d H:i:s', $item['logistics_time']) : '';
            $item['pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
            $item['brand_id'] = mGoodsBaseInfo::BRAND_MAP[$item['brand_id']];
            $item['courier_code'] = $courierArray[$item['express_company']] ?? ' ';
            $item['user_id'] = $item['uid'];
            $item['user_name'] = $userInfo[$item['uid']]['nick'] ?? '';
            unset($item['uid']);
            $downExcel->setTextFormat('I' . ($k + 1));
            $downExcel->setTextFormat('J' . ($k + 1));
        }
        $head = [
            '订单号', '商品名称', '积分价格', '积分兑换价格', '折扣价格', '零售价', '成本价', '省份', '城市', '区县', '详细地址', '收货人手机号',
            '收货人', '发货时间', '收货时间', '下单时间', '品牌', '快递公司', '快递单号', '系统邮费', '快递公司编码', '用户UID', '用户昵称'
        ];
        $downExcel->create($list, $head);
        return back();
    }

    public function downExcel(Request $request)
    {
        $params = $request->all();
        $where = $params['condition'];
        $downExcel = new DownExcel();
        $title = '批量导出';
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $list = PointOrder::getList(json_decode(base64_decode($where), true), [], ['uid', 'order_no', 'title', 'point_price', 'pay_point_price', 'discount_price', 'price',
            'cost_price', 'consignee_province', 'consignee_city', 'consignee_area', 'consignee_info_address',
            'consignee_phone_encrypt', 'consignee_name', 'logistics_time', 'confirm_time',
            'pay_time', 'brand_id', 'express_company', 'order_logistics_no', 'shipping_fee', 'good_id', 'consignee_address']);
        $list = array_values($list);
        $courierList = sShopCourier::getCourierFileList();
        $courierArray = array_column($courierList, 'trackingmore_code', 'courier_name');
        $goodsId = array_column($list, 'good_id');
        $goodsInfo = GoodsExtendInfo::extendListByGoodsId($goodsId);
        $goodsSku = array_column($goodsInfo, 'sku_code', 'goods_id');
        $uids = array_column($list, 'uid');
        $userInfo = Member::getUserList($uids, true);
        $exportList = [];
        // todo 手机号加解密
        foreach ($list as $k => $item) {
            $phone = Phone::getExtendPhone($item['consignee_phone_encrypt'], UserExtendPhoneScene::POINT_SHOP_CONSIGNEE_PHONE);
            $exportList[$k]['order_no'] = $item['order_no'];
            $exportList[$k]['pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
            $exportList[$k]['consignee_name'] = $item['consignee_name'];
            $exportList[$k]['consignee_phone_encrypt'] = $phone;
            $exportList[$k]['consignee_province'] = ShopArea::locationId2Name($item['consignee_province']);
            $exportList[$k]['consignee_city'] = ShopArea::locationId2Name($item['consignee_city']);
            $exportList[$k]['consignee_area'] = ShopArea::locationId2Name($item['consignee_area']);
            $exportList[$k]['consignee_address'] = $item['consignee_address'];
            $exportList[$k]['sku'] = $goodsSku[$item['good_id']] ?: '';
            $exportList[$k]['title'] = $item['title'];
            $exportList[$k]['good_num'] = 1;
            $exportList[$k]['price'] = number_format(bcdiv($item['price'], 100, 2), 2) . ' ';
            $exportList[$k]['cost_price'] = number_format(bcdiv($item['cost_price'], 100, 2), 2) . ' ';
            $exportList[$k]['shipping_fee'] = number_format($item['shipping_fee'], 2) . ' ';
            $exportList[$k]['point_price'] = $item['point_price'];
            $exportList[$k]['pay_point_price'] = $item['pay_point_price'];
            $exportList[$k]['discount_price'] = $item['discount_price'];
            $exportList[$k]['brand_name'] = mGoodsBaseInfo::BRAND_MAP[$item['brand_id']];
            $exportList[$k]['express_company'] = $item['express_company'] ?? ' ';
            $exportList[$k]['order_logistics_no'] = $item['order_logistics_no'] . ' ';
            $exportList[$k]['express_company_code'] = $courierArray[$item['express_company']] ?? ' ';
            $exportList[$k]['user_id'] = $item['uid'];
            $exportList[$k]['user_name'] = $userInfo[$item['uid']]['nick'] ?? '';

            $downExcel->setTextFormat('I' . ($k + 1));
            $downExcel->setTextFormat('J' . ($k + 1));
        }
        $head = [
            '订单号', '下单时间', '收货人', '收货人手机号', '省份', '城市', '区县', '详细地址', 'SKU编码', '商品名称',
            '商品数量', '零售价', '成本价', '系统邮费', '积分价格', '积分兑换价格', '折扣价格', '品牌', '快递公司', '快递单号', '快递公司编码', '用户UID', '用户昵称'
        ];
        $downExcel->create($exportList, $head);
        return back();
    }

    public function format($list)
    {
        if (is_array($list) && !empty($list)) {
            $uids = array_column($list, 'uid');
            $userInfos = Member::getUsers($uids);
            foreach ($list as &$val) {
                $phone = Phone::getExtendPhone($val['consignee_phone_encrypt'], UserExtendPhoneScene::POINT_SHOP_CONSIGNEE_PHONE);
                $coverList = json_decode($val['cover_list'], true);
                $val['cover_list'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $coverList[0], ImgUrl::IMAGE_SIZE_OP_ORI);
                $val['nick'] = $userInfos[$val['uid']]['nick'];
                $val['confirm_time'] = $val['confirm_time'] ? date('Y-m-d H:i:s', $val['confirm_time']) : '';
                $val['pay_time'] = $val['pay_time'] ? date('Y-m-d H:i:s', $val['pay_time']) : '';
                $val['consignee_phone_encrypt'] = $phone;

            }
            return $list;
        }
        return [];
    }

    public function area(Request $request)
    {
        $pid = $request->input('q', 0);
        if (empty($pid)) {
            return response()->json([]);
        }
        $data = ShopArea::locationCodeOfProvince($pid);
        $format = array_map(function ($k, $v) {
            return [
                'id' => $k,
                'text' => $v,
            ];
        }, array_keys($data), $data);
        $format = array_merge([['id' => '', 'text' => '']], $format);
        return response()->json($format);
    }

}